﻿using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.VisualTree;
using MinecraftEnchantCalculator.ViewModels;
using EnchantViewModel = MinecraftEnchantCalculator.ViewModels.Windows.MainWindowComponents.EnchantViewModel;

namespace MinecraftEnchantCalculator.Attach;

public class ListBoxSimpleMultipleSelectionAttach
{
  public static readonly AttachedProperty<bool> EnableMultipleToggleSelectionProperty =
    AvaloniaProperty.RegisterAttached<ListBoxSimpleMultipleSelectionAttach, ListBox, bool>("EnableMultipleToggleSelection");

  static ListBoxSimpleMultipleSelectionAttach()
  {
    EnableMultipleToggleSelectionProperty.Changed.AddClassHandler<ListBox>((listBox, args) => {
      if (args.NewValue is true)
        listBox.AddHandler(
          InputElement.PointerPressedEvent,
          OnPointerPressed,
          RoutingStrategies.Tunnel,
          false);
      else
        listBox.RemoveHandler(InputElement.PointerPressedEvent, OnPointerPressed);
    });
  }

  public static void SetEnableMultipleToggleSelection(
    AvaloniaObject element, bool value
  )
  {
    element.SetValue(EnableMultipleToggleSelectionProperty, value);
  }

  public static bool GetEnableEnableMultipleToggleSelection(
    AvaloniaObject element
  )
  {
    return element.GetValue(EnableMultipleToggleSelectionProperty);
  }

  private static void OnPointerPressed(
    object? sender, PointerPressedEventArgs e
  )
  {
    if (sender is not ListBox listBox) return;

    var pt = e.GetCurrentPoint(listBox);
    if (!pt.Properties.IsLeftButtonPressed) return;

    if (listBox.InputHitTest(pt.Position) is not Control hit) return;

    if (hit.FindAncestorOfType<Button>() != null ||
        hit.FindAncestorOfType<CheckBox>() != null ||
        hit.FindAncestorOfType<Slider>() != null ||
        hit.FindAncestorOfType<ToggleSwitch>() != null ||
        hit.FindAncestorOfType<ScrollBar>() != null)
      return;

    var item = hit.FindAncestorOfType<ListBoxItem>();

    e.Handled = true;
    if (item?.DataContext is not EnchantViewModel evm)
      return;
    evm.IsSelected = !evm.IsSelected;
  }
}